<script setup>
import Avatar from "@/components/Avatar.vue";
import CommentImage from "@/views/Article/CommentImage.vue";
import CommentPost from "@/views/Article/CommentPost.vue";
import {ref, computed} from "vue";
import router from "@/router/index.js";
import { commentAPI } from "@/apis/index.js";
import { ElMessage } from "element-plus";

const props = defineProps({
  articleId: {
    type: Number,
  },
  commentData: {
    type: Object,
  },
  articleUserId: {
    type: Number,
  },
  currentUserInfo: {
    type: Object,
  },
  allowComment: {
    type: Boolean,
    default: true
  },
});

// 定义事件
const emit = defineEmits(['refresh-comments']);

const pCommentId = ref(0);
const replyUserId = ref(null);

const subReplyPanel =ref(false);

// 子评论折叠状态管理
const isChildrenCollapsed = ref(false);

// 计算显示的子评论数量
const displayedChildren = computed(() => {
  if (!props.commentData.children || props.commentData.children.length === 0) {
    return [];
  }

  if (props.commentData.children.length > 1 && isChildrenCollapsed.value) {
    return props.commentData.children.slice(0, 1);
  }
  
  return props.commentData.children;
});

// 是否需要显示折叠/展开按钮
const shouldShowCollapseButton = computed(() => {
  return props.commentData.children && props.commentData.children.length > 1;
});

// 初始化折叠状态
if (props.commentData.children && props.commentData.children.length > 1) {
  isChildrenCollapsed.value = true;
}

// 切换子评论折叠状态
const toggleChildrenCollapse = () => {
  isChildrenCollapsed.value = !isChildrenCollapsed.value;
};

// 回复面板显示
const showReplyPanel = (comment, type) => {
  const targetPCommentId = type === 0 ? comment.commentId : comment.pCommentId;
  const targetReplyUserId = type === 0 ? 0 : comment.userId;

  if (pCommentId.value === targetPCommentId && replyUserId.value === targetReplyUserId) {
    subReplyPanel.value = !subReplyPanel.value;
  } else {
    pCommentId.value = targetPCommentId;
    replyUserId.value = targetReplyUserId;
    subReplyPanel.value = true;
  }
}

// 点赞
const doLike = async (data) => {
  try {
    const response = await commentAPI.likeComment({
      commentId: data.commentId
    });
    
    if (response.status === 'success') {
      // 更新点赞状态
      data.likeType = data.likeType === 1 ? 0 : 1;
      // 更新点赞数量
      if (response.data && response.data.goodCount !== undefined) {
        data.goodCount = response.data.goodCount;
      } else {
        data.goodCount = data.likeType === 1 ? data.goodCount + 1 : data.goodCount - 1;
      }
      
      // 显示成功消息
      if (data.likeType === 1) {
        ElMessage.success('Like successful');
      } else {
        ElMessage.success('Unlike successful');
      }
    }
  } catch (error) {
    console.error(error);
  }
}

// 置顶评论操作
const opTop = async (comment) => {
  try {
    const newTopType = comment.topType === 0 ? 1 : 0;
    const response = await commentAPI.changeTopType({
      commentId: comment.commentId,
      topType: newTopType
    });
    
    if (response.status === 'success') {
      comment.topType = newTopType;
      ElMessage.success(newTopType === 1 ? 'Set top successful' : 'Cancel top successful');
    }
  } catch (error) {
    console.log(error)
  }
}

// 评论发布完成回调
const postCommentFinish = () => {
  subReplyPanel.value = false;
  emit('refresh-comments');
}

const gotoUcenter = (userId) => {
  router.push(`/user/${userId}`)
}
</script>

<template>
  <div class="comment-item">
    <Avatar :src="commentData.avatar" :width="50" @click="gotoUcenter(commentData.userId)"></Avatar>
    <div class="comment-info">
      <div class="nick-name">
        <span class="name" @click="gotoUcenter(commentData.userId)">
          {{commentData.nickName }}
        </span>
        <span class="tag-author" v-if="commentData.userId == articleUserId">Author</span>
        <span class="tag-self" v-else-if="commentData.userId == currentUserInfo.userId">Self</span>
      </div>
      <div class="comment-content">
        <div>
          <span class="tag tag-topping" v-if="commentData.topType == 1">Top</span>
          <span v-if="commentData && commentData.content" v-html="commentData.content.replace(/\n/g, '<br>')"></span>
        </div>
        <CommentImage
            :style="{ 'margin-top': '10px' }"
            v-if="commentData.imgPath"
            :src="commentData.imgPath"
        ></CommentImage>
      </div>
      <!--下方面板-->
      <div class="op-panel">
<!--        时间-->
        <div class="time">
          <span>{{ commentData.postTime }}</span>
        </div>
<!--        点赞-->
        <div
            :class="['icon', commentData.likeType === 1 ? 'active' : '']"
            @click="doLike(commentData)"
        >
          <el-icon><Star /></el-icon>
          <span>{{ commentData.goodCount > 0 ? commentData.goodCount : "Like" }}</span>
        </div>
<!--        回复-->
        <div
            class="icon"
            @click="showReplyPanel(commentData, 0)"
        >
          <el-icon><ChatDotRound /></el-icon>
          <span>Reply</span>
        </div>
<!--        设置置顶-->
        <el-dropdown v-if="articleUserId == currentUserInfo.userId">
          <el-icon><More /></el-icon>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="opTop(commentData)">
                {{ commentData.topType == 0 ? "Set Top" : "Cancel Top" }}
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
<!--      回复的回复-->
      <div class="comment-sub-list" v-if="commentData.children">
        <div class="comment-sub-item" v-for="sub in displayedChildren" :key="sub.commentId">
          <Avatar :src="sub.avatar" :width="30"></Avatar>
          <div class="comment-sub-info">
            <div class="nick-name">
              <span class="name" @click="gotoUcenter(sub.userId)">
                {{sub.nickName }}
              </span>
              <span class="tag-author" v-if="sub.userId === articleUserId">Author</span>
              <span class="tag-self" v-else-if="sub.userId == currentUserInfo.userId">Self</span>
              <span class="reply-name">Reply</span>
              <span @click="gotoUcenter(sub.replyUserId)" class="a-link">@{{ sub.replyNickName }}</span>
              <span>：</span>
              <div v-if="sub && sub.content" v-html="sub.content.replace(/\n/g, '<br>')"></div>
            </div>
            <div class="sub-image">
              <CommentImage
                  :style="{ 'margin-top': '10px' }"
                  v-if="sub.imgPath"
                  :src="sub.imgPath"
              ></CommentImage>
            </div>
            <div class="op-panel">
              <div class="time">
                <span>{{ sub.postTime }}</span>
              </div>
<!--              点赞-->
              <div
                  :class="['icon',sub.likeType == 1 ? 'active' : '',]"
                  @click="doLike(sub)"
              >
                <el-icon><Star /></el-icon>
                {{ sub.goodCount > 0 ? sub.goodCount : "Like" }}
              </div>
<!--              评论-->
              <div
                  class="icon"
                  @click="showReplyPanel(sub, 1)"
              >
                <el-icon><ChatDotRound /></el-icon>
                <span>Reply</span>
              </div>
            </div>
          </div>
        </div>
        <!-- 折叠/展开按钮 -->
        <div class="collapse-toggle" v-if="shouldShowCollapseButton">
          <div class="collapse-btn" @click="toggleChildrenCollapse">
            <span v-if="isChildrenCollapsed">
              Expand ({{ commentData.children.length - 1 }} more replies)
            </span>
            <span v-else>
              Hide reply
            </span>
            <el-icon class="collapse-icon" :class="{ 'expanded': !isChildrenCollapsed }">
              <ArrowDown />
            </el-icon>
          </div>
        </div>
        <div class="reply-info" v-if="subReplyPanel">
          <CommentPost
              :articleId="articleId"
              :pCommentId="pCommentId"
              :replyUserId="replyUserId"
              :avatarWidth="30"
              :userInfo="currentUserInfo"
              :allowComment="allowComment"
              :showInsertImg="false"
              @comment-published="postCommentFinish"
          ></CommentPost>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.comment-item {
  display: flex;
  padding-top: 15px;
  .comment-info {
    flex: 1;
    margin-left: 10px;
    border-bottom: 1px solid #ddd;
    .nick-name {
      .name {
        font-size: 16px;
        color: var(--text2);
        margin-right: 10px;
        cursor: pointer;
      }
      .tag-author {
        background: var(--pink);
        color: #fff;
        font-size: 12px;
        border-radius: 2px;
        padding: 0px 3px;
      }
      .tag-self {
        background: var(--link);
        color: #fff;
        font-size: 12px;
        border-radius: 2px;
        padding: 0px 3px;
      }
    }
    .comment-content {
      margin-top: 5px;
      font-size: 16px;
      line-height: 22px;
      .tag {
        margin-right: 5px;
        font-size: 15px;
        border-radius: 3px;
        padding: 2px 5px;
      }
      .tag-topping {
        color: var(--pink);
        border: 1px solid var(--pink);
      }
      .no-audit {
        color: var(--text2);
        border: 1px solid var(--text2);
      }
    }

    .comment-sub-list {
      margin-top: 10px;
      .comment-sub-item {
        display: flex;
        margin: 8px 0px;
        font-size: 16px;
        .comment-sub-info {
          margin-left: 5px;
          .nick-name {
            .reply-name {
              margin: 0px 5px;
            }
            .sub-content {
              font-size: 16px;
            }
          }
        }
      }
    }

    .op-panel {
      display: flex;
      align-items: center;
      margin-top: 5px;
      font-size: 16px;
      color: var(--text2);
      .time {
        margin-right: 20px;
      }
      .icon {
        display: flex;
        margin-right: 15px;
        align-items: center;
        font-size: 16px;
        color: var(--icon);
        cursor: pointer;
      }
      .icon::before {
        margin-right: 3px;
      }
      .active {
        color: var(--link);
      }
    }
    .reply-info {
      margin-top: 15px;
    }

    .collapse-toggle {
      margin-top: 10px;
      padding: 5px 0;
      
      .collapse-btn {
        width: 300px;
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 8px 12px;
        background: #f5f5f5;
        border: 1px solid #e0e0e0;
        border-radius: 4px;
        cursor: pointer;
        font-size: 14px;
        color: var(--text2);
        transition: all 0.3s ease;
        
        &:hover {
          background: #ebebeb;
          border-color: #d0d0d0;
          color: var(--link);
        }
        
        .collapse-icon {
          margin-left: 5px;
          transition: transform 0.3s ease;
          
          &.expanded {
            transform: rotate(180deg);
          }
        }
      }
    }
  }
}
</style>